/** Deprecated module
 * Writed for dummy simulation of std::vector just for ability of retrieving 
 * pointer to the content of vector. Later it was discovered that same thing
 * exists in std::vector:
 * 
 * vector<int> v;
 * const int *v = &v[0];
 */
#ifndef _FRACTAL_FDYNAMICARRAY_H_
#define _FRACTAL_FDYNAMICARRAY_H_


#include <iostream>
using namespace std;


template <class Type>
class FDynamicArray
{
public:
    FDynamicArray(int size=0, const Type &val=Type())
    {
	_capacity = _size = 0;
	this->resize(size, val);
    }

    FDynamicArray(const Type *vals, int size)
    {
	_capacity = _size = 0;
	this->reserve(size);
	copy(_buf, _buf + size, vals);
    }

    FDynamicArray(const FDynamicArray &that)
    {
	_capacity = _size = 0;
	this->reserve(that._size);
	copy(that._buf, that._buf+that._size, _buf);
	_size = that._size;
    }

    ~FDynamicArray(void)
    {
	if (_capacity)
	    delete[] _buf;
    }

    FDynamicArray &
    operator=(const FDynamicArray &that)
    {
	if (this == &that)
	    return *this;

	this->reserve(0);
	this->reserve(that._capacity);

	copy(that._buf, that._buf+that._size, _buf);
	_size = that._size;
	return *this;
    }

    Type &
    operator[](int pos)
    {
	return *(_buf + pos);
    }

    void reserve(int n=0)
    {
	if (n < 0)
	    n = 0;
	if (_capacity)
	    delete[] _buf;
	_buf = new Type[n];
	_capacity = n;
	_size = 0;
    }

    void resize(int new_size, const Type &val=Type())
    {
	if (new_size < 0)
	    new_size = 0;

	Type *buf = new Type[new_size];
	// copy existing vertices
	if (_size <= new_size) {
	    // new size bigger => copy all existing vertices
	    copy(_buf, _buf+_size, buf);
            // fill tail by default val
	    fill(buf+_size, buf+new_size, val);
	}
	else
	    // new size smaller => copy new_size existing vertices
	    copy(_buf, _buf+new_size, buf);
	// replace _buf by new buf
	this->reserve(0);
	_buf = buf;
	_size = new_size;
	_capacity = new_size;
    }

    int size(void) const
    {
	return _size;
    }

    void push_back(const Type &val)
    {
	if (_size == _capacity)
	    this->resize(_size+1, val);
	else
	    _buf[_size++] = val;
    }

    const Type * c_ptr(void) const
    {
	return _buf;
    }

private:
    Type *_buf;
    int _capacity, _size;
};


#endif  // _FRACTAL_FDYNAMICARRAY_H_
